<template>
	<el-form
		class="pointAndRebate"
		:model="values"
		ref="pointAndRebateForm"
		:label-width="labelWidth"
	>
		<el-form-item
			label="分润模式:"
			prop="commissionModel"
			class="commissionModel"
			:required="isEdit"
			v-if="isCommission === false"
		>
			<el-col :span="12">
				<el-select
					v-if="isAdd"
					@change="handleModelChange"
					v-model="commissionModel"
					placeholder="请选择佣金模式"
					style="width: 100%;"
				>
					<el-option label="返点模式" :value="1"></el-option>
					<el-option label="返佣模式" :value="2"></el-option>
				</el-select>
				<span v-else>
					{{
						parseInt(commissionModel) === 1
							? '返点模式'
							: '返佣模式'
					}}
				</span>
			</el-col>
		</el-form-item>

		<!-- 返点比例分配模式 -->
		<el-form-item
			label="返点比例分配模式:"
			prop="rebateAllotMode"
			class="rebateAllotMode"
			v-if="commissionModel === 1 && !isVip"
			:required="isEdit || isAgentEdit"
			:rules="[
				{
					required: isEdit || isAgentEdit,
					message: '请选择返点比例分配模式',
					trigger: ['blur', 'change']
				}
			]"
		>
			<el-col :span="12">
				<el-select
					v-if="isEdit || isAgentEdit"
					v-model="rebateAllotMode"
					@change="handleRebateAllotModeChange"
					placeholder="请选择返点比例分配模式"
					style="width: 100%;"
				>
					<el-option label="自由配置" :value="1"></el-option>
					<el-option label="模板分配" :value="2"></el-option>
				</el-select>
				<span v-else>
					{{
						parseInt(rebateAllotMode) === 1
							? '自由配置'
							: '模板分配'
					}}
				</span>
			</el-col>
		</el-form-item>

		<!-- 返点比例模板 模板分配下展示 -->
		<el-form-item
			label="返点比例模板:"
			prop="rebateRateTemplateId"
			class="rebateRateTemplateId"
			v-if="commissionModel === 1&& rebateAllotMode === 2 && !isVip"
			:required="isEdit || isAgentEdit"
			:rules="[
				{
					required: isEdit || isAgentEdit,
					message: '请选择返点比例模板',
					trigger: ['blur', 'change']
				}
			]"
		>
			<el-col :span="12">
				<el-select
					v-if="isEdit || isAgentEdit"
					v-model="rebateRateTemplateId"
					placeholder="请选择返点比例模板"
					style="width: 100%;"
					@change="handleChangeTemplate"
				>
					<el-option
						v-for="item in templateList"
						:label="item.templateName"
						:value="item.id"
						:key="item.id"
					>
					</el-option>
				</el-select>
				<span v-else>
					{{ rebateRateTemplateName || rebateRateTemplateId }}
				</span>
			</el-col>
		</el-form-item>

		<!-- 返点比例 -->
		<template v-if="commissionModel === 1 || isVip">
			<!-- isVip 修改会员返水比例 -->
			<template v-if="isVip">
				<el-form-item
					class="pointTable"
					style="max-width: 1100px;"
					:isEdit="isMemberEdit || isEdit"
					prop="commissionModel"
					label="平台发放返水比例:"
				>
					<PointTable
						:commissionModel="0"
						:isEdit="isMemberEdit || isEdit"
						:platformFlag="1"
						v-model="rebateRateList[1]"
						:checkMax="_checkMax"
					/>
				</el-form-item>
				<el-form-item
					class="pointTable"
					style="max-width: 1100px;"
					:required="isEdit"
					prop="commissionModel"
					label="代理发放返水比例:"
				>
					<PointTable
						:commissionModel="0"
						:isEdit="false"
						:platformFlag="1"
						v-model="rebateRateList[0]"
						:checkMax="_checkMax"
					/>
				</el-form-item>
			</template>
			<template v-else>
				<el-form-item
					prop="commissionModel"
					label="团队返点比例:"
					:required="isEdit"
					class="pointTable"
					style="max-width: 1100px;"
					v-if="rebateAllotMode === 1 || (rebateAllotMode === 2 && rebateRateTemplateId)"
					:isEdit="_isAgentEdit"
				>
					<PointTable
						:commissionModel="commissionModel"
						:isEdit="_isAgentEdit"
						:platformFlag="0"
						v-model="rebateRateList[0]"
						:checkMax="_checkMax"
					/>
				</el-form-item>
				<el-form-item
					v-if="isTotalAgent"
					class="pointTable"
					style="max-width: 1100px;"
					:required="isMemberEdit || isEdit"
					prop="commissionModel"
					label="默认会员返水比例(平台发放):"
				>
					<PointTable
						:commissionModel="0"
						:isEdit="isMemberEdit || isEdit"
						:platformFlag="1"
						v-model="rebateRateList[1]"
						:checkMax="_checkMax"
					/>
				</el-form-item>
			</template>
		</template>

		<!-- 返佣 -->
		<template v-else>
			<el-form-item
				v-if="isCommission === false"
				class="pointTable"
				style="max-width: 1100px;"
				prop="commissionModel"
				label="默认会员返水比例(平台发放):"
			>
				<PointTable
					:commissionModel="commissionModel"
					:isEdit="isEdit"
					v-model="rebateRateList[1]"
					:platformFlag="1"
					:checkMax="_checkMax"
				/>
			</el-form-item>

			<el-form-item
				style="max-width: 1350px;"
				:rules="[commissionRateListRule]"
				prop="commissionRateList"
				label="该代理团队返佣比例："
			>
				<RebateTable
					:checkMax="_checkMax"
					:isEdit="isEdit"
					:clearValidate="clearValidate"
					v-model="commissionRateList"
					ref="RebateTable"
				/>
			</el-form-item>
		</template>
	</el-form>
</template>

<script>
import RebateTable from './RebateTable.vue'
import PointTable from './PointTable.vue'

const initRateValue = (otherParams = {}) => ({
	texasRebate: undefined,
	sportsRebate: undefined,
	actualPersonRebate: undefined,
	esportsRebate: undefined,
	lotteryTicketRebate: undefined,
	chessRebate: undefined,
	texasInsuranceRebate: undefined,
	userType: otherParams.platformFlag === 1 ? 0 : 1,
	...otherParams
})

export default {
	name: 'PointAndRebate',
	components: {
		PointTable,
		RebateTable
	},
	props: {
		data: {
			type: Object,
			default: () => ({})
		},
		isAgentEdit: {
			type: Boolean,
			default: false
		},
		isMemberEdit: {
			type: Boolean,
			default: false
		},
		isAdd: {
			type: Boolean,
			default: false
		},
		isEdit: {
			type: Boolean,
			default: false
		},
		labelWidth: {
			type: String,
			default: '230px'
		},
		isTotalAgent: {
			type: Boolean,
			default: true
		},
		// 会员修改
		isVip: {
			type: Boolean,
			default: false
		},
		// 只展示返佣信息
		isCommission: {
			type: Boolean,
			default: false
		},
		checkMax: {
			type: Function,
			default: null
		},
		merchantId: {
			type: String,
			default: undefined
		}
	},
	data() {
		return {
			// 下标0 是平台 下标1是代理
			rebateRateList: [
				initRateValue({ platformFlag: 0 }),
				initRateValue({ platformFlag: 1 })
			],
			commissionRateList: [],
			commissionModel: 1,
			rebateAllotMode: 2,
			rebateRateTemplateId: undefined,
			maxRateListVals: [
				{platformFlag: 0},
				{platformFlag: 1}
			],
			maxVals: {},
			rebateRateTemplateName: undefined,
			templateList: []
		}
	},
	computed: {
		_isAgentEdit() {
			if (this.isAgentEdit && this.rebateAllotMode === 1) {
				return true
			}
			if (this.isEdit && this.rebateAllotMode === 1) {
				return true
			}

			return false
		},
		commissionRateListRule() {
			return {
				required: this.isEdit,
				message: '请添加代理团队返佣比例',
				trigger: 'change'
			}
		},
		values() {
			const vals = {
				commissionRateList: this.commissionRateList,
				commissionModel: this.commissionModel,
				rebateRateList: this.rebateRateList,
				rebateAllotMode: this.rebateAllotMode,
				rebateRateTemplateId: this.rebateRateTemplateId
			}
			return vals
		}
	},
	watch: {
		data: {
			immediate: true,
			deep: true,
			handler(newData) {
				if (!newData || Object.keys(newData).length === 0) {
					return
				}
				for (const key in this.rebateValues) {
					this.rebateValues[key] = newData[key]
				}
				this.commissionModel = newData['commissionModel'] || 1
				this.commissionRateList = newData['commissionRateList'] || []
				this.rebateAllotMode = newData.rebateAllotMode || 1
				this.rebateRateTemplateId = newData.rebateRateTemplateId
				this.rebateRateTemplateName = newData.rebateRateTemplateName
				if (
					newData['rebateRateList'] &&
					newData['rebateRateList'].length > 0
				) {
					this.rebateRateList = newData['rebateRateList']?.map((obj) => {
						return {...obj}
					})
				}
			}
		},
		commissionModel: {
			immediate: true,
			deep: true,
			handler(num) {
				this.rebateRateList[0].userType = num === 2 ? 0 : 1
				// 返佣
				if (num === 2) {
					this.queryLimit({
						platformFlag: 1,
						commissionMode: num
						// userType: 0
					})
				} else {
					// 返点
					this.queryLimit({
						platformFlag: 0,
						commissionMode: num
						// userType: 1
					})
					this.queryLimit({
						platformFlag: 1,
						commissionMode: num
						// userType: 0
					})
				}
			}
		},
		merchantId: {
			deep: true,
			handler(newMerchantId) {
				this.rebateRateTemplateId = undefined
				this.queryRateTemplateList({
					merchantId: newMerchantId
				})
			}
		}
	},
	mounted() {
		this.rateQueryLimit()
		this.validate = this.$refs['pointAndRebateForm'].validate
		if (this.merchantId) {
			this.queryRateTemplateList({
				merchantId: this.merchantId
			})
		}
	},
	methods: {
		_checkMax(field, value) {
			const path = field.split('.') || []
			if (this.checkMax && typeof this.checkMax === 'function') {
				return this.checkMax(field, value)
			}
			// 返点判断最多输入限制
			if (path.length >= 2) {
				const index = parseInt(path[1])
				const key = path[2]
				const max = this.maxRateListVals?.[index]?.[key]
				if (typeof max === 'number' && Number(value) > max) {
					return `不能大于${max}`
				}
			} else {
				const max = this.maxVals[field]
				if (typeof max === 'number' && Number(value) > max) {
					return `不能大于${max}`
				}
			}
			return false
		},
		clearValidate(prop) {
			this.$refs['pointAndRebateForm'].clearValidate(prop)
		},
		async resetFields() {
			this.rebateRateList = [
				initRateValue({ platformFlag: 0 }),
				initRateValue({ platformFlag: 1 })
			]
			this.commissionRateList = []
			if (this.$refs['RebateTable']) {
				this.$refs['RebateTable'].handleInit()
			}
			this.clearValidate()
			this.$refs['pointAndRebateForm'].resetFields()
		},
		pointChange(value) {
			this.values = value
		},
		getValues() {
			const values = Object.assign({}, this.values)

			// 获取模板名称
			if (values.rebateRateTemplateId && this.templateList.length > 0) {
				this.templateList.forEach(templ => {
					if (templ.id === values.rebateRateTemplateId) {
						values['rebateRateTemplateName'] = templ.templateName
					}
				})
			}

			// 返点
			if (this.commissionModel === 1) {
				delete values.commissionRateList

				// if (this.rebateAllotMode === 2) {
				// 	values.rebateRateList = [values.rebateRateList[1]]
				// }
			}
			// 返佣
			if (this.commissionModel === 2) {
				const rebate = values.rebateRateList[1]
				// delete rebate.platformFlag
				rebate.userType = rebate.userType === undefined ? 2 : rebate.userType
				values.rebateRateList = [rebate]
			}
			return values
		},
		handleModelChange(val) {
			this.resetFields()
		},
		handleRebateAllotModeChange(val) {
			if (val === 1) {
				// for (const key in this.rebateRateList[0]) {
				// 	if (!['id', 'userType'].includes(key)) {
				// 		this.rebateRateList[0][key] = undefined
				// 	}
				// }
				// this.rebateRateList[0]['userType'] = 1
				// this.rebateRateList[0]['platformFlag'] = 0
				// this.rebateRateTemplateId = undefined
			}
			if (val === 2) {
				this.queryRateTemplateList()
			}
		},
		async handleChangeTemplate(id) {
			const res = await this.$api.rebateRateTemplateDetailQuery({
				templateId: id,
				level: 1
			})

			// 更新团队返点
			if (res.code === 200 && res.data) {
				const tempRates = res.data[0] || {}

				for (const key in this.rebateRateList[0]) {
					// 切换模板时id不覆盖
					if (key !== 'id') {
						this.rebateRateList[0][key] = tempRates[key]
					}
				}
				this.rebateRateList[0]['userType'] = 1
				this.rebateRateList[0]['platformFlag'] = 0
			}
		},
		async queryLimit(params) {
			const { platformFlag = 0 } = params
			const res = await this.$api.rebateRateQueryLimit(params)
			if (res.code === 200 && res.data) {
				this.maxRateListVals[platformFlag] = res.data
			}
		},
		async rateQueryLimit() {
			const res = await this.$api.commissionRateQueryLimit()
			if (res.code === 200) {
				for (const key in res.data) {
					if (res.data[key]) {
						this.maxVals[key] = res.data[key]
					}
				}
			}
		},
		async queryRateTemplateList(params) {
			if (!params.merchantId) {
				this.templateList = []
				this.rebateRateTemplateId = undefined
				return
			}
			const res = await this.$api.rebateRateTemplateQueryList({
				pageNum: 1,
				pageSize: 999,
				...(params || {})
			})
			if (res.code === 200) {
				this.templateList = res.data.record || []
			}
		}
	}
}
</script>

<style>
.pointAndRebate td .el-form-item__error {
	top: auto;
	bottom: 0px;
	left: 0;
}

.pointAndRebate td .el-form-item__content {
	height: 53px;
}
</style>
